package common

import (
	"context"
	"fmt"
	"github.com/gogf/gf/v2/frame/g"
	"hotgo/api/admin/common"
	"hotgo/internal/dao"
	"hotgo/internal/model/entity"
	"hotgo/internal/model/input/adminin"
	"hotgo/internal/service"

	"github.com/gogf/gf/v2/errors/gerror"
)

var Operation = cOperation{}

type cOperation struct{}

func (c *cOperation) OpenMember(ctx context.Context, req *common.OpenMemberReq) (res *common.OpenMemberRes, err error) {

	mb := &entity.AdminMember{}
	model := dao.AdminMember.Ctx(ctx)
	if req.ID != 0 {
		model = model.Where("id = ?", req.ID)
	} else {
		model = model.Where("mobile = ?", req.Mobile)
	}
	err = model.Scan(&mb)
	if mb.Id == 0 && err != nil {
		err = gerror.New("暂未找到该用户")
		return
	}

	err = service.AdminMember().OpenMember(ctx, &adminin.OpenMemberInp{
		MemberId: mb.Id,
		CardId:   1,
	})
	if err != nil {
		err = gerror.Wrap(err, "开通会员失败")
		return
	}
	return nil, nil
}

func (c *cOperation) QueryOldTicket(ctx context.Context, req *common.QueryOldTicketReq) (res *common.QueryOldTicketRes, err error) {
	mb, err := service.AdminMember().GetById(ctx, &adminin.GetByIdInp{Id: req.ID})
	if err != nil {
		err = gerror.Wrap(err, "获取用户信息失败")
		return
	}
	if mb.Mobile == "" {
		err = gerror.New("用户手机号为空")
		return
	}
	data, err := g.DB("xiuxian_db").Raw(fmt.Sprintf(`
		SELECT 
			COALESCE(SUM(special_count_remain), 0)::TEXT AS "specialTicket",
			CONCAT(
				COALESCE(SUM(general_count_remain), 0), 
				' + ', 
				min(c.use_num), 
				' (会员可使用次数) - ', 
				(SELECT COUNT(1)
				 FROM users_appointment z 
				 WHERE z.uid = min(c.uid) 
				   AND appointment_date >= TO_DATE(TO_CHAR(min(c.start_time), 'YYYY-MM-DD'), 'YYYY-MM-DD') 
				   AND appointment_date <= TO_DATE(TO_CHAR(min(c.expire_time), 'YYYY-MM-DD'), 'YYYY-MM-DD') 
				   AND status IN (0,1,4)  -- 预约中，已预约，已完成
				   AND card_id = 0),
				   ' (已预约次数)'
			) AS "generalTicket"
		FROM 
			users_invite_card a
			LEFT JOIN users b ON a.uid = b.id
			LEFT JOIN users_member c ON a.uid = c.uid
		WHERE
			b.phone = '%s'
			AND a.expire_time > CURRENT_TIMESTAMP
    `, mb.Mobile)).One()
	if err != nil {
		err = gerror.Wrap(err, "查询旧系统券数失败")
		return
	}
	err = data.Struct(&res)
	return
}
